package statistics;

import java.util.Random;

/**
 * This class represents an Erlang distribution.
 * @author Marko Boon
 * @version 2.0
 */

public class ErlangDistribution extends ContinuousDistribution {

  protected double lambda;
  protected int shape;

  /**
   * Constructs an Erlang distribution. 
   * @param shape the shape of the Erlang distribution
   * @param lambda the intensity
   */
   
  public ErlangDistribution(int shape, double lambda) {
    this(shape, lambda, new Random());
  }
  
  /**
   * Constructs an Erlang distribution. 
   * @param shape the shape of the Erlang distribution
   * @param lambda the intensity
   * @param random the random number generator
   */
   
  public ErlangDistribution(int shape, double lambda, Random random) {
    this.lambda = lambda;
    this.shape = shape;
    this.random = random;
  }
  
  /**
   * Returns the distribution function
   */ 
   
  public double probabilityFunction(double x) {
    return 1.0 - (new PoissonDistribution(lambda*x)).probabilityFunction(shape-1);
  } 
  
  public double expectation() {
    return shape / lambda;
  }
  
  public double variance() {
    return shape/lambda/lambda;
  }
  
  /**
   * Returns the lambda parameter
   * @return lambda
   */
  
  public double getLambda() {
    return lambda;
  }
  
  /**
   * Returns the shape parameter
   * @return shape
   */
   
  public int getShape() {
    return shape;
  }
  
  public double nextRandom() {
    double r = 0.0;
    ExponentialDistribution d = new ExponentialDistribution(lambda, random);
    for (int i = 0; i < shape; i++) {
      r += d.nextRandom();
    }
    return r;
  }
}
    
    
